#include "base_logger.h"
#include <iostream>

std::map<std::string, std::shared_ptr<spdlog::logger>> base_logger::loggers_;
std::mutex base_logger::logger_mutex_;

std::shared_ptr<spdlog::logger> base_logger::registerLogger(
    const std::string& module,
    const std::string& log_path,
    const std::string& log_name,
    spdlog::level::level_enum level,
    size_t max_file_size,
    size_t max_files,
    Mode mode)
{
    std::lock_guard<std::mutex> lock(logger_mutex_);

    // 日志文件路径拼接，跨平台
    boost::filesystem::path dir(log_path);
    if (!boost::filesystem::exists(dir)) {
        boost::filesystem::create_directories(dir);
    }
    boost::filesystem::path file = dir / log_name;
    std::string full_path = file.string();

    // 唯一标识：模块名+路径+文件名
//    std::string logger_key = module + "|" + full_path;

    auto it = loggers_.find(module);
    if (it != loggers_.end()) {
        return it->second;
    }

    std::shared_ptr<spdlog::logger> logger;
    if (mode == Mode::Async) {
        auto sink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>(full_path, max_file_size, max_files);
        logger = std::make_shared<spdlog::async_logger>(
            module, sink, spdlog::thread_pool(), spdlog::async_overflow_policy::block);
        spdlog::register_logger(logger);
    } else {
        //同步模式自动注册
        logger = spdlog::rotating_logger_mt(module, full_path, max_file_size, max_files);

    }
    logger->set_level(level);
    logger->set_pattern("[%Y-%m-%d %H:%M:%S.%e][%l][%n] %v");
    logger->flush_on(level);

    // 修正2: 使用module参数而不是硬编码"deam_ui"
    // warnning : get 函数不支持跨模块dll 中注册，exe 中不能用
    auto retrieved_logger = spdlog::get(module);
    if (retrieved_logger) {
        retrieved_logger->info("Logger initialized successfully");
    } else {
        std::cout << "Failed to retrieve logger: " << module << std::endl;
    }

    // 可选：设置为默认logger
    //spdlog::set_default_logger(logger);

    loggers_[module] = logger;
    return logger;
}

std::shared_ptr<spdlog::logger> base_logger::getLogger(const std::string &name)
{
   std::lock_guard<std::mutex> lock(logger_mutex_);
   auto it = loggers_.find(name);
   return (it != loggers_.end()) ? it->second : nullptr;
}
